<template>
  <van-icon
    size="24"
    name="back-top"
    class="top-box"
    v-show="show"
    @click="handleToTop"
  />
</template>
<script lang="ts" setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import _ from 'lodash'

const show = ref(false)
const handleToTop = () => {
  window.scrollTo({
    top: 0,
    behavior: 'smooth'
  })
}

const scrollHandler = () => {
  const scrollTop = document.body.scrollTop || document.documentElement.scrollTop
  show.value = scrollTop > window.screen.height / 2
}

onMounted(() => {
  window.addEventListener('scroll', _.throttle(scrollHandler, 100))
})

onBeforeUnmount(() => {
  document.removeEventListener('scroll', _.throttle(scrollHandler, 100))
})
</script>
<style lang="scss" scoped>
.top-box {
  position: fixed;
  bottom: 20px;
  right: 20px;
  z-index: 20;
  background: #459bf3;
  color: #fff;
  padding: 10px;
  border-radius: 99px;
  box-shadow: 0px 6px 12px 0px rgba(146, 200, 255, 0.44);
}
</style>
